package com.cuit.mimall.service.impl;

import com.cuit.mimall.common.R;
import com.cuit.mimall.dto.LoginRequest;
import com.cuit.mimall.entity.LoginUser;
import com.cuit.mimall.service.LoginService;
import com.cuit.mimall.util.JwtUtil;
import com.cuit.mimall.util.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author TeaWu
 */ /*
 * LoginServiceImpl实现类
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;

    private final RedisCache redisCache;

    @Autowired
    public LoginServiceImpl(AuthenticationManager authenticationManager, RedisCache redisCache) {
        this.authenticationManager = authenticationManager;
        this.redisCache = redisCache;
    }

    @Override
    public String login(LoginRequest loginRequest) {
        //从loginRequest中获取信息,判断是用户名登录,还是邮箱登录,还是手机号登录
        String userName = loginRequest.getUserName();
        String email = loginRequest.getEmail();
        // 如果用户名不为空,则使用用户名登录
        if (userName != null) {
            log.info("用户名登录");
        }
        // 通过UsernamePasswordAuthenticationToken获取用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginRequest.getUserName(), loginRequest.getPassword());
        try {
            // AuthenticationManager委托机制对authenticationToken 进行用户认证
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            // 如果认证通过，拿到这个当前登录用户信息
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            // 获取当前用户的userid
            String userId = loginUser.getUser().getUserId().toString();
            String jwt = JwtUtil.createJwt(userId);
            Map<String, String> map = new HashMap<>();
            map.put("token", jwt);
            // 把完整的用户信息存入redis userid为key 用户信息为value
            redisCache.setCacheObject("login:" + userId, loginUser);
            redisCache.setCacheObject(userId, map.toString());
            log.info("登录成功,当前登录用户为:{},权限为:{}", loginUser.getUser().getNickName(), loginUser.getPermissions());
            return jwt;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public R<?> logout() {
        //从SecurityContextHolder中的userid
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getUserId();

        //根据userid找到redis对应值进行删除
        if (redisCache.deleteObject("login:" + userid)) {
            return new R<>(200, "注销成功");
        } else {
            return new R<>(500, "注销失败");
        }
    }

}